package game.views;

import motion.easing.Linear;
import motion.Actuate;
import hx.display.Graphics;
import hx.geom.Point;
import hx.display.Box;

/**
 * 角色四象限组件
 * 上攻
 * 下防
 * 左敏
 * 右易
 */
@:build(hx.macro.UIBuilder.build("assets/views/RoleAttr4.xml"))
class RoleAttr4 extends Box {
	/**
	 * 攻
	 */
	private var __v1:Float = 0;

	/**
	 * 防
	 */
	private var __v2:Float = 0;

	/**
	 * 敏
	 */
	private var __v3:Float = 0;

	/**
	 * 易
	 */
	private var __v4:Float = 0;

	override function onInit() {
		super.onInit();
		this.p1.originX = -p1.width / 2 + 3;
		this.p1.originY = -p1.height / 2 + 3;
		this.p2.originX = -p2.width / 2 + 3;
		this.p2.originY = -p2.height / 2 + 3;
		this.p3.originX = -p3.width / 2 + 3;
		this.p3.originY = -p3.height / 2 + 3;
		this.p4.originX = -p4.width / 2 + 3;
		this.p4.originY = -p4.height / 2 + 3;
		// 随机绘制
		// 攻
		// var v1 = (Std.random(5) + 1) / 5;
		// 防
		// var v2 = (Std.random(5) + 1) / 5;
		// 敏
		// var v3 = (Std.random(5) + 1) / 5;
		// 易
		// var v4 = (Std.random(5) + 1) / 5;
	}

	/**
	 * 展示能力值
	 * @param v1 
	 * @param v2 
	 * @param v3 
	 * @param v4 
	 */
	public function show(v1:Float, v2:Float, v3:Float, v4:Float):Void {
		Actuate.update(draw, 0.5, [__v1, __v2, __v3, __v4], [v1, v2, v3, v4]);
	}

	private var __g:Graphics;

	/**
	 * 绘制能量条
	 * @param v1 
	 * @param v2 
	 * @param v3 
	 * @param v4 
	 */
	private function draw(v1:Float, v2:Float, v3:Float, v4:Float):Void {
		__v1 = Math.min(Math.max(0.1, v1), 5);
		__v2 = Math.min(Math.max(0.1, v2), 5);
		__v3 = Math.min(Math.max(0.1, v3), 5);
		__v4 = Math.min(Math.max(0.1, v4), 5);
		// 线的长度
		var len = 150;
		// 计算点
		var v1p = mathVPoint(len * v1, -90);
		var v2p = mathVPoint(len * v2, 90);
		var v3p = mathVPoint(len * v3, -180);
		var v4p = mathVPoint(len * v4, 0);

		// 绘制形状
		if (__g == null)
			__g = new Graphics();
		var g = __g;
		// 绘制图形
		g.clear();
		g.beginFill(0x00ffff);
		g.drawTriangles([
			v1p.x, v1p.y, v4p.x, v4p.y, v3p.x, v3p.y, v4p.x, v4p.y, v2p.x, v2p.y, v3p.x, v3p.y
		], [0, 1, 2, 2, 3, 4], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0.5);
		// 绘制线条
		g.beginLineStyle(0x00ffff, 3);
		g.moveTo(v1p.x, v1p.y);
		g.lineTo(v3p.x, v3p.y);
		g.lineTo(v2p.x, v2p.y);
		g.lineTo(v4p.x, v4p.y);
		g.lineTo(v1p.x, v1p.y);
		if (g.x == 0) {
			this.updateLayout();
			g.x = this.attr4.x + this.attr4.width / 2;
			g.y = this.attr4.y + this.attr4.height / 2;
			this.box.addChildAt(g, 0);
		}
		this.p1.x = g.x + v1p.x;
		this.p1.y = g.y + v1p.y;
		this.p2.x = g.x + v2p.x;
		this.p2.y = g.y + v2p.y;
		this.p3.x = g.x + v3p.x;
		this.p3.y = g.y + v3p.y;
		this.p4.x = g.x + v4p.x;
		this.p4.y = g.y + v4p.y;
	}

	/**
	 * 计算能量条的位置
	 * @param len 
	 * @param rotation 
	 * @return Point
	 */
	private function mathVPoint(len:Float, rotation:Float):Point {
		var r = Point.rotationToRadian(rotation);
		var cos = Math.cos(r);
		var sin = Math.sin(r);
		return new Point(len * cos, len * sin);
	}
}
